package com.xsf.jieyou.cloud.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Redis配置类
 *
 * @author xsf
 * @version v1.0.0
 * @date 2019/11/19
 **/
@Configuration
public class RedisConfig {
    /**
     * 配置 RedisTemplate 序列化器
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        //创建 RedisTemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        //定义Jackson序列化器
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //定义String序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        //设置 Redis 中的 String 类型的 key 的序列化器
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //设置 Redis 中的 Hash 类型的 key 的序列化器
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //设置 Redis 中的 String 类型的 value 的序列化器
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //设置 Redis 中的 Hash 类型的 value 的序列化器
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    /**
     * 密码加密器
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
